package com.wuseguang.springcloud.service.impl;

import com.wuseguang.springcloud.dao.jdbc.ActivityJdbc;
import com.wuseguang.springcloud.dao.repository.ActivityRepository;
import com.wuseguang.springcloud.dao.repository.EnrolledStudentsRepository;
import com.wuseguang.springcloud.entity.Activity;
import com.wuseguang.springcloud.entity.EnrolledStudents;
import com.wuseguang.springcloud.service.ActivityService;
import com.wuseguang.springcloud.util.CodeUtil;
import com.wuseguang.springcloud.util.PaginationUtil;
import com.wuseguang.springcloud.util.PagingTool;
import com.wuseguang.springcloud.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 活动表 服务实现类
 * </p>
 *
 * @author 
 * @since 2020-05-11
 */
@Service
public class ActivityServiceImpl  implements ActivityService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private ActivityJdbc activityJdbc;
    @Autowired
    private ActivityRepository activityRepository;
    @Autowired
    private EnrolledStudentsRepository enrolledStudentsRepository;


    @Override
    public Result findSignedUpActivity(Integer studentId, Integer type, Integer indexNo, Integer rows) {

        logger.info("查询学生的活动");

        String sql = "select a.id,a.title,DATE_FORMAT(activity_start_time,'%Y-%m-%d %T') activity_start_time " +
               ",DATE_FORMAT(activity_end_time,'%Y-%m-%d %T') activity_end_time," +
               " DATE_FORMAT(enrollment_start_time,'%Y-%m-%d %T')enrollment_start_time," +
               "  DATE_FORMAT(enrollment_end_time,'%Y-%m-%d %T') enrollment_end_time,a.highlights," +
                "a.activity_content,a.cost,a.quota,a.push,a.url,a.signed_up ,es.id es_id, " +
                "(CASE WHEN es.state=1 THEN 6   WHEN NOW()<a.enrollment_start_time  THEN 0  " +
                "WHEN NOW()>a.activity_end_time THEN 5  WHEN NOW()>=a.activity_start_time THEN 4 " +
                "WHEN a.quota>0 and a.quota=a.signed_up THEN 3 WHEN NOW()>a.enrollment_end_time THEN 2   ELSE 1  END ) state " +
                "from activity a left join enrolled_students es on(es.activity_id=a.id) where  es.student_id = ? and es.state = ? ORDER BY a.id desc";

        List<Map<String,Object>> list = activityJdbc.queryListMap(sql,studentId,type);

        //创建分页工具
        PagingTool tool = new PagingTool();
        //放入页码
        tool.setIndexNo(indexNo);
        //放入每页显示数量
        tool.setRows(rows);
        //放入角色集合
        tool.setList(list);
        //返回数据
        return new Result(new PaginationUtil<>(list.size(), rows, tool.getList(), indexNo));
    }

    @Transactional
    @Override
    public Result activitySignUpOrCancel(String studentId, Integer id, Integer type) {
        logger.info("活动报名或者取消报名");

        //报名信息保证数据统一
        synchronized (this){
            //获取这个报名信息
            Activity a = activityRepository.findById(id).get();

            //如果报名时间已过期
            if(a.getEnrollmentEndTime().getTime()<new Date().getTime()){
                logger.info("报名时间已过");
                return new Result(CodeUtil.REGISTRATION_TIME_HAS_PASSED);
            }


            String signUpOrCancel = "";

            //判断如果报名等于取消
            if(type==0){
                logger.info("取消报名");
                a.setSignedUp(a.getSignedUp()-1);
                a.setState(1);
                signUpOrCancel = ",registration_time = null ";
            }else{
                logger.info("报名");
                //判断此活动是否限额，并且已经满额
                if(a.getQuota() !=0 &&  a.getQuota()==a.getSignedUp()){
                    logger.info("名额已满");
                    a.setState(3);
                    activityRepository.save(a);
                    return new Result(CodeUtil.THE_QUOTA_IS_FULL);
                }
                a.setSignedUp(a.getSignedUp()+1);
                signUpOrCancel = ",registration_time = now() ";
            }
            activityRepository.save(a);

            //修改学生报名状态
            String sql = "UPDATE `enrolled_students` SET `state` = ? "+signUpOrCancel+"   WHERE `student_id` = ? and activity_id = ?";
            activityJdbc.updateByParameter(sql,type,studentId,id);


            return new Result();
        }

    }

    @Override
    public Result findActivityDetails(Integer id,Integer studentId) {

        //查询活动详情
        String sql = "select a.id,a.title,DATE_FORMAT(activity_start_time,'%Y-%m-%d %T') activity_start_time " +
                ",DATE_FORMAT(activity_end_time,'%Y-%m-%d %T') activity_end_time," +
                " DATE_FORMAT(enrollment_start_time,'%Y-%m-%d %T')enrollment_start_time," +
                "  DATE_FORMAT(enrollment_end_time,'%Y-%m-%d %T') enrollment_end_time,a.highlights," +
                "a.activity_content,a.cost,a.quota,a.push,a.url,a.signed_up ,es.id es_id, " +
                " (CASE WHEN es.state=1 THEN 6   WHEN NOW() > a.activity_end_time " +
                "THEN 5 WHEN NOW() < a.activity_end_time and NOW() >= a.activity_start_time THEN 4  " +
                " WHEN NOW() < a.enrollment_start_time THEN 0 WHEN NOW() > a.enrollment_end_time " +
                " THEN 2  WHEN a.state = 3 THEN 3 ELSE 1 END ) state " +
                "from activity a left join enrolled_students es on(es.activity_id=a.id) where a.id = ? and es.student_id = ?";


        Map<String,Object> map = null;
        try{
            //查询信息
            map =  activityJdbc.queryMap(sql,id,studentId);
        }catch (Exception e){
            map = new HashMap<>();
        }

        return new Result(map);
    }
}
